<?php

namespace model;
require_once __DIR__ . '/../utils/MysqlDBUtils.php';

use utils\MysqlDBUtils;

class BookCategoryModel
{
    private $dbUtil;

    public function __construct()
    {
        $this->dbUtil = new MysqlDBUtils();
    }

    /**
     * 获取分类下的图书列表（带分页和搜索）
     * @param int $categoryId 分类ID
     * @param string $q 搜索关键词
     * @param int $currentPage 当前页
     * @param int $perPage 每页显示数量
     * @return array 包含books、total、currentPage等的分页数据
     */
    public function getPaginatedBooks(int $categoryId, string $q = '', int $currentPage = 1, int $perPage = 8): array
    {
        // 安全转义输入（防止SQL注入）
        $categoryId = intval($categoryId); // 强制转为整数
        $escapedQ = $this->dbUtil->escapeString($q); // 使用MysqlDBUtils的转义方法

        // 构造WHERE条件
        $where = "WHERE b.category_id = $categoryId";
        if (!empty($escapedQ)) {
            $where .= " AND (b.title LIKE '%$escapedQ%' OR b.isbn LIKE '%$escapedQ%' OR b.author LIKE '%$escapedQ%')";
        }
        // 查询总记录数
        $totalSql = "SELECT COUNT(*) AS total 
                    FROM book b 
                    LEFT JOIN book_category bc ON b.category_id = bc.id 
                    $where";
        $totalResult = $this->dbUtil->prepareQuery($totalSql);
        $total = $totalResult ? $totalResult[0]['total'] : 0;

        // 计算分页偏移量
        $offset = ($currentPage - 1) * $perPage;
        $booksSql = "SELECT b.*, bc.category_name 
                    FROM book b 
                    LEFT JOIN book_category bc ON b.category_id = bc.id 
                    $where 
                    LIMIT $offset, $perPage";
        $books = $this->dbUtil->prepareQuery($booksSql);

        return [
            'books' => $books ?? [],
            'total' => $total,
            'currentPage' => $currentPage,
            'perPage' => $perPage,
            'totalPages' => max(1, ceil($total / $perPage))
        ];
    }

    public function getAllCategories()
    {
        $sql = "select * from book_category";
        return $this->dbUtil->prepareQuery($sql);
    }

    /**
     * 获取分类下的图书列表
     * @param int $currentPage 当前页
     * @param int $perPage 每页显示数量
     * @return array 当前页和每页显示数量, 分类列表
     */
    public function getPaginatedCategories(int $currentPage = 1, int $perPage): array
    {
        $totalSql='select count(*) as total from book_category';
        $totalResult=$this->dbUtil->prepareQuery($totalSql);
        $total=$totalResult? $totalResult[0]['total']:0;
        $offset=($currentPage-1)*$perPage;
        $sql="select * from book_category limit $offset,$perPage";
        $categories=$this->dbUtil->prepareQuery($sql);
        return [
            'categories'=>$categories??[],
            'total'=>$total,
            '$currentPage'=>$currentPage,
            'perPage'=>$perPage,
            'totalPages'=>max(1,ceil($total/$perPage))
        ];
    }

}

?>